package com.kili.cloud.shorturl.controller;

import com.kili.cloud.common.util.IpUtil;
import com.kili.cloud.shorturl.enumerate.VisitTypeEnum;
import com.kili.cloud.shorturl.service.ShortUrlService;
import com.kili.cloud.shorturl.vo.InputReturnVO;
import com.kili.cloud.shorturl.vo.ShortUrlParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: tom.liu
 * @date: 2019/6/16 23:48
 */
@RestController
@Api(tags="短链接服务控制类",value="短链接服务控制类")
public class ShortUrlController {

    @Autowired
    ShortUrlService shortUrlService;

    @Value("${shorturl.entity}")
    String shortUrlDomain;

    @Value("${shorturl.maxInputCount}")
    Long shortUrlMaxInputCount;

    @Value("${shorturl.maxVisitCount}")
    Long shortUrlMaxVisitCount;

    @PostMapping("/normalInput")
    @ApiOperation(value="正常模式下的长链接转短链接方法")
    public InputReturnVO normalInput(@RequestBody ShortUrlParam param){
        return shortUrlService.input(param, VisitTypeEnum.NORMAL.getCode(), shortUrlMaxInputCount, shortUrlDomain);
    }

    @GetMapping("/normalVisit")
    @ApiOperation(value="正常模式下的访问短链接方法")
    public void  normalVisit(String uri, HttpServletRequest request, HttpServletResponse response)throws Exception{
        String url = shortUrlService.visit(uri, IpUtil.getIpAddr(request), shortUrlMaxVisitCount);
        String http = "http://";
        String https = "https://";
        //如果原url不包含协议
        if(!url.contains(http) && !url.contains(https)){
            url = http + url;
        }
        response.sendRedirect(url);
    }

    @PostMapping("/simpleInput")
    @ApiOperation(value="试用模式下的长链接转短链接方法")
    public InputReturnVO simpleInput(ShortUrlParam param){
        return shortUrlService.input(param, VisitTypeEnum.TRY.getCode(), shortUrlMaxInputCount, shortUrlDomain);
    }

    @GetMapping("/simpleVisit")
    @ApiOperation(value="试用模式下的访问短链接方法")
    public String simpleVisit(String uri, HttpServletRequest request){
        String url = shortUrlService.visit(uri, IpUtil.getIpAddr(request), shortUrlMaxVisitCount);
        return "redirect:" + url;
    }


}
